Routing is a mechanism to map incoming HTTP requests to specific controller actions. Understanding routing is crucial for managing URL patterns and making your app user-friendly and SEO-optimized.
Routes in ASP.NET Core are configured in Program.cs
(or Startup.cs
in earlier versions) using the app.MapControllerRoute
method, which defines how URLs map to controllers and actions.
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
{controller=Home}/{action=Index}/{id?}
:{controller=Home}
: Specifies the controller, defaulting to Home
.{action=Index}
: Specifies the action method, defaulting to Index
.{id?}
: Optional parameter for passing an id
.[Route("products")]
public class ProductsController : Controller
{
[HttpGet("all")]
public IActionResult GetAllProducts() { /*...*/ }
[HttpGet("{id}")]
public IActionResult GetProductById(int id) { /*...*/ }
}
app.MapControllerRoute(name: "custom", pattern: "{controller=Products}/{action=List}/{id:int:min(1)}");
{id:int:min(1)}
ensures id
is an integer greater than or equal to 1.bool
, datetime
, guid
, minlength(x)
, maxlength(x)
, and custom regular expressions.app.MapControllerRoute(name: "gallery", pattern: "Gallery/{action=Main}/{id?}",defaults: new { controller = "Gallery" });
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(name: "productDetail", pattern: "products/details/{id:int}/{name}");
This structure allows URLs like /products/details/10/laptop
, which is clear and keyword-rich.
Controllers are central in ASP.NET Core MVC and handle requests, retrieve data, and determine how it’s returned to the client.
HomeController
, ProductController
).Controller
base class and contains action methods.public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
[HttpGet]
, [HttpPost]
, [HttpPut]
, and [HttpDelete]
to specify which HTTP methods they handle.[HttpPost]
public IActionResult CreateProduct(Product product)
{
//Handle POST request
return RedirectToAction("Index");
}
public class ProductsController : Controller
{
private readonly IProductRepository _repository;
public ProductsController(IProductRepository repository)
{
_repository = repository;
}
}
}
public IActionResult EditProduct(int id, string name) {
// Parameters are bound from the URL }